package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.dto.PracticeSummaryDTO;
import com.example.computer_exam_training_sys.entity.UserStudyStatistics;
import com.example.computer_exam_training_sys.entity.UserStudyStatisticsWithAnalysis;
import com.example.computer_exam_training_sys.service.UserAnalysisService;
import com.example.computer_exam_training_sys.service.UserLearningProgressService;
import com.example.computer_exam_training_sys.service.UserPracticeService;
import com.example.computer_exam_training_sys.service.UserStudyStatisticsService;
import com.example.computer_exam_training_sys.vo.LearningProgressVO;
import com.example.computer_exam_training_sys.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/api/statistics")
public class UserStudyStatisticsController {

    @Autowired
    private UserStudyStatisticsService statisticsService;
    
    @Autowired
    private UserPracticeService practiceService;
    
    @Autowired
    private UserLearningProgressService learningProgressService;
    
    @Autowired
    private UserAnalysisService analysisService;

    @GetMapping("/daily/{userId}")
    public ResponseEntity<UserStudyStatisticsWithAnalysis> getDailyStatistics(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        return ResponseEntity.ok(statisticsService.findByUserIdAndDateWithAnalysis(userId, date));
    }

    @GetMapping("/range/{userId}")
    public ResponseEntity<List<UserStudyStatisticsWithAnalysis>> getDateRangeStatistics(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        return ResponseEntity.ok(statisticsService.findByUserIdAndDateRangeWithAnalysis(userId, startDate, endDate));
    }

    @PostMapping("/record/{userId}")
    public ResponseEntity<Void> recordStatistics(
            @PathVariable Long userId,
            @RequestParam Integer studyTime,
            @RequestParam Integer questionCount,
            @RequestParam Integer correctCount,
            @RequestParam Integer practiceCount,
            @RequestParam Integer examCount) {
        UserStudyStatistics statistics = new UserStudyStatistics();
        statistics.setUserId(userId);
        statistics.setStatisticsDate(LocalDate.now());
        statistics.setTotalStudyTime(studyTime);
        statistics.setQuestionCount(questionCount);
        statistics.setCorrectCount(correctCount);
        statistics.setPracticeCount(practiceCount);
        statistics.setExamCount(examCount);
        statisticsService.recordStatistics(statistics);
        return ResponseEntity.ok().build();
    }
    
    @PostMapping("/update-from-records/{userId}")
    public ResponseEntity<Result<String>> updateStatisticsFromRecords(
            @PathVariable Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        if (date == null) {
            date = LocalDate.now();
        }
        statisticsService.updateStatisticsFromPracticesAndExams(userId, date);
        return ResponseEntity.ok(Result.success("统计数据已从练习和考试记录更新"));
    }
    
    @PostMapping("/batch-update/{userId}")
    public ResponseEntity<Result<String>> batchUpdateStatistics(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        if (endDate == null) {
            endDate = LocalDate.now();
        }
        
        // 遍历日期范围，更新每一天的统计数据
        LocalDate currentDate = startDate;
        int updatedDays = 0;
        
        while (!currentDate.isAfter(endDate)) {
            statisticsService.updateStatisticsFromPracticesAndExams(userId, currentDate);
            currentDate = currentDate.plusDays(1);
            updatedDays++;
        }
        
        return ResponseEntity.ok(Result.success("已更新 " + updatedDays + " 天的统计数据"));
    }

    @GetMapping("/trend/time/{userId}")
    public ResponseEntity<Map<String, List<Object>>> getStudyTimeTrend(@PathVariable Long userId) {
        return ResponseEntity.ok(statisticsService.getStudyTimeTrend(userId));
    }

    @GetMapping("/trend/questions/{userId}")
    public ResponseEntity<Map<String, List<Object>>> getQuestionCountTrend(@PathVariable Long userId) {
        return ResponseEntity.ok(statisticsService.getQuestionCountTrend(userId));
    }

    @GetMapping("/trend/correct-rate/{userId}")
    public ResponseEntity<Map<String, Object>> getCorrectRateTrend(@PathVariable Long userId) {
        return ResponseEntity.ok(statisticsService.getCorrectRateTrend(userId));
    }
    
    /**
     * 获取用户练习统计数据，按照课程和知识点进行分组
     */
    @GetMapping("/practice/{userId}")
    public ResponseEntity<Map<String, Object>> getPracticeStatistics(@PathVariable Long userId) {
        // 获取用户所有练习记录
        List<com.example.computer_exam_training_sys.vo.UserPracticeCourseVO> practices = 
            practiceService.selectPracticeCourseByUserId(userId.intValue());
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalPractices", practices.size());
        
        // 统计总体正确率
        int totalQuestions = 0;
        int totalCorrect = 0;
        
        for (com.example.computer_exam_training_sys.vo.UserPracticeCourseVO practice : practices) {
            totalQuestions += practice.getQuestionCount();
            totalCorrect += practice.getCorrectCount();
        }
        
        double accuracy = totalQuestions > 0 ? 
                (double) totalCorrect / totalQuestions * 100 : 0;
                
        result.put("overallAccuracy", Math.round(accuracy * 100.0) / 100.0);
        result.put("practices", practices);
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取指定课程或知识点的练习摘要信息
     */
    @GetMapping("/practice-summary/{userId}")
    public ResponseEntity<PracticeSummaryDTO> getPracticeSummary(
            @PathVariable Long userId,
            @RequestParam Integer pointId) {
        
        PracticeSummaryDTO summary = practiceService.getPracticeSummary(userId.intValue(), pointId);
        return ResponseEntity.ok(summary);
    }
    
    /**
     * 更新用户学习进度
     */
    @PostMapping("/update-learning-progress/{userId}")
    public ResponseEntity<Result<String>> updateLearningProgress(
            @PathVariable Long userId,
            @RequestParam Long courseId,
            @RequestParam Double completionRate,
            @RequestParam Integer studyTime) {
        
        learningProgressService.updateCourseLearningProgress(userId, courseId, completionRate, studyTime);
        return ResponseEntity.ok(Result.success("学习进度已更新"));
    }
    
    /**
     * 获取用户学习进度概览
     */
    @GetMapping("/learning-progress/{userId}")
    public ResponseEntity<LearningProgressVO> getLearningProgressOverview(@PathVariable Long userId) {
        LearningProgressVO overview = learningProgressService.getProgressOverview(userId);
        return ResponseEntity.ok(overview);
    }
    
    /**
     * 获取用户课程学习进度
     */
    @GetMapping("/course-progress/{userId}")
    public ResponseEntity<List<com.example.computer_exam_training_sys.dto.LearningProgressDTO>> getCourseProgress(
            @PathVariable Long userId) {
        
        List<com.example.computer_exam_training_sys.dto.LearningProgressDTO> courseProgress = 
            learningProgressService.getCourseProgress(userId);
            
        return ResponseEntity.ok(courseProgress);
    }
    
    /**
     * 同步更新用户统计数据、学习进度和分析数据
     */
    @PostMapping("/sync-all-data/{userId}")
    public ResponseEntity<Map<String, Object>> syncAllUserData(
            @PathVariable Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        
        if (date == null) {
            date = LocalDate.now();
        }
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 更新统计数据
            statisticsService.updateStatisticsFromPracticesAndExams(userId, date);
            result.put("statisticsUpdated", true);
            
            // 2. 自动更新所有课程的学习进度
            try {
                learningProgressService.autoUpdateAllProgress(userId);
                result.put("progressUpdated", true);
            } catch (Exception e) {
                result.put("progressUpdated", false);
                result.put("progressError", e.getMessage());
            }
            
            // 3. 生成或更新用户分析数据
            try {
                Map<String, Object> analysisResult = analysisService.getUserOverallAnalysis(userId.intValue());
                result.put("analysisUpdated", analysisResult != null && !analysisResult.isEmpty());
                result.put("analysisData", analysisResult);
            } catch (Exception e) {
                result.put("analysisUpdated", false);
                result.put("analysisError", e.getMessage());
            }
            
        } catch (Exception e) {
            result.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取用户学习数据综合分析
     */
    @GetMapping("/comprehensive-analysis/{userId}")
    public ResponseEntity<Map<String, Object>> getComprehensiveAnalysis(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 统计数据
            Double correctRate = statisticsService.getCorrectRate(userId);
            Integer totalStudyTime = statisticsService.getTotalStudyTime(userId);
            
            result.put("correctRate", correctRate);
            result.put("totalStudyTime", totalStudyTime);
            
            // 2. 学习进度
            LearningProgressVO progressOverview = learningProgressService.getProgressOverview(userId);
            result.put("learningProgress", progressOverview);
            
            // 3. 薄弱知识点分析
            LearningProgressVO weakPointsAnalysis = learningProgressService.getWeakPointsAnalysis(userId);
            result.put("weakPointsAnalysis", weakPointsAnalysis);
            
            // 4. 用户整体分析
            Map<String, Object> overallAnalysis = analysisService.getUserOverallAnalysis(userId.intValue());
            result.put("overallAnalysis", overallAnalysis);
            
            // 5. 薄弱知识点组合
            String combinedWeakPoints = analysisService.getCombinedWeakPoints(userId.intValue());
            result.put("weakPoints", combinedWeakPoints);
            
        } catch (Exception e) {
            result.put("error", e.getMessage());
            return ResponseEntity.ok(result);
        }
        
        return ResponseEntity.ok(result);
    }
} 